package thread;

//结合FutureTask使用

import java.util.concurrent.*;

public class Test3_Callable {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        //方式1：内部类
        FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
            //功能：累加和
            @Override
            public Integer call() throws Exception {
                int count = 0;
                for (int i =0 ;i<100;i++){
                    Thread.sleep(100);
                    count+=i;
//                    if (i == 10){
//                        throw new RuntimeException("error");
//                    }
                }
                return count;
            }
        });
        //将任务与线程绑定
        Thread t1 = new Thread(task);
        t1.start();
        //取返回值
        System.out.println("结果:"+task.get());
//        System.out.println("结果:"+task.get(1, TimeUnit.SECONDS));


        //lambda写法
        FutureTask<Integer> task2 = new FutureTask<>(()->{
            int count = 0;
            for (int i =0 ;i<100;i++){
                Thread.sleep(10);
                count+=i;
//                    if (i == 10){
//                        throw new RuntimeException("error");
//                    }
            }
            return count;
        });
        Thread t2 = new Thread(task2);
        t2.start();
        System.out.println("结果2:"+task2.get());
    }
}
